import React, { Component } from 'react'
/*
  使用受控组件的步骤
  1、在类组件中定义state数据
  2、在表单组件中使用value属性来设置state数据
  3、在表单组件中绑定onChange事件,并且设置回调函数
  4、将接受到的e.target.value的值通过setState来改变state中的数据
*/
export default class App extends Component {
  state={
    uname:'Giles',
    password:'',
    telephoy:[]
  }
  handleUserName=(e)=>{
    this.setState(()=>{
      return{
        uname:e.target.value
      }
    },()=>{
      console.log(this.state.uname);
    })
  }
  handlePwd=(e)=>{
    this.setState(()=>{
      return{
        password:e.target.value
      }
    })
  }
  handleCk=(e)=>{
    if(e.target.checked){
      this.state.telephoy.push(e.target.value)
      this.setState(()=>{
        return{
          telephoy:this.state.telephoy
        }
      },()=>{
        console.log(this.state.telephoy);
      })
    }else{
      let index=this.state.telephoy.indexOf(e.target.value)
      this.state.telephoy.splice(index,1)
      this.setState(()=>{
        return{
          telephoy:this.state.telephoy
        }
       },()=>{
        console.log(this.state.telephoy);
       })
    }
  }
  register=()=>{
    console.log(this.state);
  }
  render() {
    return (
      <div>
        <div>
          <label htmlFor="username">姓名:</label>
          <input type="text" id='username' value={this.state.uname} onChange={this.handleUserName}/>
        </div>
        <div>
          <label htmlFor='pwd'>密码:</label>
          <input type="password" id='pwd' value={this.state.password} onChange={this.handlePwd}/>
        </div>
        <div>
           <label htmlFor="telephony">掌握的技能:</label>
           <input type="checkbox" value="HTML5" onChange={this.handleCk}/>HTML5
           <input type="checkbox" value="javascript" onChange={this.handleCk}/>javascript
           <input type="checkbox" value="vue" onChange={this.handleCk}/>vue
           <input type="checkbox" value="react" onChange={this.handleCk}/>react
        </div>
        <div>
          <button onClick={this.register}>注册</button>
        </div>
      </div>  
    )
  }
}  
